/**
 * 
 */
package org.t2.backstage.module.gameserver.service;

import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.banish.sql.core.datasource.IDataSource;
import org.gaming.service.asserts.Asserts;
import org.gaming.service.repository.database.DBConfig;
import org.gaming.service.repository.database.MySqlDataSource;
import org.gaming.service.repository.database.ErrorDataBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.t2.backstage.module.TipsCode;
import org.t2.backstage.module.gameserver.model.GameDb;
import org.t2.backstage.module.gameserver.model.GameServer;

/**
 * @author YY
 *
 */
@Service
public class DataBaseManager {
	
	@Autowired
	private GameServerService gameServerService;
	@Autowired
	private GameDbService gameDbService;
	
	//日志库的数据库连接
	private ConcurrentMap<Integer, IDataSource> logDbMap = new ConcurrentHashMap<>();
	//TODO 多长时间断开连接
	
	public IDataSource getLogDb(int gameServerUniqueId) {
		IDataSource dataBase = logDbMap.get(gameServerUniqueId);
		if(dataBase == null) {
			synchronized (this) {
				dataBase = logDbMap.get(gameServerUniqueId);
				if(dataBase == null) {
					//TODO 初始化
					GameServer gameServer = gameServerService.getEntity(0L, gameServerUniqueId);
					Asserts.isTrue(gameServer != null, TipsCode.GAME_SERVER_MISS, gameServerUniqueId);
					
					GameDb gameDb = gameDbService.getDb(gameServer.getDbLogName());
					if(gameDb == null) {
						return null;
					}
					
					DBConfig dbConfig = new DBConfig();
					dbConfig.setId(gameServerUniqueId);
					dbConfig.setUser(gameDb.getUser());
					dbConfig.setPassword(gameDb.getPassword());
					dbConfig.setIpPort(gameDb.getIpPort());
					dbConfig.setDbName(gameDb.getDbName());
					try {
						dataBase = new MySqlDataSource(dbConfig);
					} catch (Exception e) {
						dataBase = new ErrorDataBase(dbConfig);
					}
					logDbMap.put(gameServerUniqueId, dataBase);
				}
			}
		}
		if(dataBase instanceof ErrorDataBase) {
			return null;
		}
		return dataBase;
	}
	
	public void cleanErroDataBase() {
		Set<Integer> deleteKeys = new HashSet<>();
		for(Entry<Integer, IDataSource> entry : logDbMap.entrySet()) {
			if(entry.getValue() instanceof ErrorDataBase) {
				deleteKeys.add(entry.getKey());
			}
		}
		for(int key : deleteKeys) {
			logDbMap.remove(key);
		}
	}
}
